import Http from "../../../utils/http.js";
import Utils from '../../../utils/util.js';
import WxValidate from '../../../utils/WxValidate';
const app = getApp();

function transferInfo(obj, usePropertyRange, colorDicts) {
  usePropertyRange.forEach((item, index, self) => {
    if (item.code == obj.useProperty) {
      obj.useProperty = item
    }
  });
  colorDicts.forEach((item, index, self) => {
    if (item.code == obj.color) {
      obj.color = item
    }
  });
  return obj;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //
    carInfoForVin: "",

    //单个车型进来后数据的存储
    info: "",

    opts: "",
    isDisabled: true,


    colorDicts: [],

    isRefresh:false,
    //步骤进度
    progressStep: 1,
    //日期选择的范围
    dateRangeStart: "1990-01-01",
    dateRangeEnd: Utils.formatDate(new Date()),
    dateRangeEndPlugin: Utils.formatDate(new Date(), 1),
    //vin
    vin: "",
    //配置亮点描述
    detailHighlight: "",
    //使用性质
    useProperty: "",
    usePropertyRange: "",
    usePropertyIndex: "",
    //初登日期
    registerDate: "",

    modelId: "",
    // /opt/tc/images/temp/20200412/e6d56f2972573afb9a4a5172ba67c3d2.jpg
    licenseImgOcr: "",
    licenseImgOcrBase64: "",
    licenseImgOcrFullSrc: "",

    //车辆类型
    carType: 0,
    carTypeRange: [{
        name: '二手车',
        value: '0',
        checked: 'true'
      },
      {
        name: '新车',
        value: '1',
        disabled: true
      }
    ],

    //所属城市
    location: "",

    name: "",
    //过户次数
    transferTimesIndex: "",
    transferTimesRange: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
    //钥匙数量
    keyNumIndex: "",
    keyNumRange: [1, 2, 3, 4, 5],
    //出厂日期
    productionDate: "",
    //商业险有效期
    commerciaInsuranceDate: "",
    mandatoryInsuranceDate: "",
    //年检有效期
    examinationDate: "",
    //排放标准字段
    emissionStandard: "",
    emissionStandardRange: "",
    emissionStandardIndex: "",

    //车身颜色
    color: {

    },

    //车况描述是否可见
    remarkVisible: "0",
    remarkVisibleRange: [{
        name: '不可见',
        value: '0',
        checked: 'true'
      },
      {
        name: '可见',
        value: '1'
      }
    ],
    //左前图片上传后返回的地址
    vehicleImagesLeftFrontImg: "",
    vehicleImagesLeftFrontImgBase64: "",
    vehicleImagesLeftFrontImgFullSrc: "",
    //右后
    vehicleImagesRightBackImg: "",
    vehicleImagesRightBackImgBase64: "",
    vehicleImagesRightBackImgFullSrc: "",

    //中控
    vehicleImagesConsoleImg: "",
    vehicleImagesConsoleImgBase64: "",
    vehicleImagesConsoleImgFullSrc: "",
    //座椅
    vehicleImagesSeatImg: "",
    vehicleImagesSeatImgBase64: "",
    vehicleImagesSeatImgFullSrc: "",

    //发动机舱
    vehicleImagesEngineImg: "",
    vehicleImagesEngineImgBase64: "",
    vehicleImagesEngineImgFullSrc: "",

    //后备箱
    vehicleImagesTrunkImg: "",
    vehicleImagesTrunkImgBase64: "",
    vehicleImagesTrunkImgFullSrc: "",

    vcLicenseImg: "",
    vcLicenseImgBase64: "",
    vcLicenseImgFullSrc: "",


    vcRegistration12Img: "",
    vcRegistration12ImgBase64: "",
    vcRegistration12ImgFullSrc: "",

    vcRegistrationLastImg: "",
    vcRegistrationLastImgBase64: "",
    vcRegistrationLastImgFullSrc: "",

    otherImgsStr: "",
    otherImgsStrBase64: [],
    otherImgsArr: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options", options)
    this.setData({
      opts: options
    });
    if ((options.code == "DRAFT" && options.id) || !options.id) {
      this.setData({
        isDisabled: false
      })
    }
    this._initValidate();
    /**
     * 获取运营的性质字典
     */
    Http.request({
      url: '/dict/findDict',
      method: 'GET',
      data: {
        category: 'VEHICLE_USE_PROPERTY',
      },
      success: (res) => {
        this.setData({
          useProperty: res
        });
        if (res.length) {
          let resRange = [];
          let resRangeCode = [];
          res.forEach((item, index, self) => {
            resRange.push(item.name);
            resRangeCode.push(item.code);
          });
          this.setData({
            usePropertyRange: resRange,
            resRangeCode: resRangeCode
          });
        }
      }
    });


    /**
     * 获取排放标准字典
     */
    Http.request({
      url: '/dict/findDict',
      method: 'GET',
      data: {
        category: 'VEHICLE_EMISSION_STANDARD',
      },
      success: (res) => {
        this.setData({
          emissionStandard: res
        });
        if (res.length) {
          let resRange = [];
          res.forEach((item, index, self) => {
            resRange.push(item.name)
          });
          this.setData({
            emissionStandardRange: resRange
          });
        }
      }
    });

    /**
     * 获取运营的性质字典
     */
    Http.request({
      url: '/dict/findDict',
      method: 'GET',
      data: {
        category: 'VEHICLE_COLOR',
      },
      success: (res) => {
        console.log("color字典", res)
        this.setData({
          colorDicts: res
        })
      }
    });


  },
  onShow: function () {
     
  },
  pageForToggleRefresh:function(isRefresh){
      if(isRefresh){
        this.setData({
          isRefresh:true
        });
        this.setData({
            progressStep:1,
            //单个车型进来后数据的存储
            info: "",
            opts: "",
          
            isRefresh:false,
            //步骤进度
            progressStep: 1,
            //日期选择的范围
            dateRangeStart: "1990-01-01",
            dateRangeEnd: Utils.formatDate(new Date()),
            dateRangeEndPlugin: Utils.formatDate(new Date(), 1),
            //vin
            vin: "",
            //配置亮点描述
            detailHighlight: "",
            //使用性质
           
            usePropertyIndex: "",
            //初登日期
            registerDate: "",
        
            modelId: "",
            // /opt/tc/images/temp/20200412/e6d56f2972573afb9a4a5172ba67c3d2.jpg
            licenseImgOcr: "",
            licenseImgOcrBase64: "",
            licenseImgOcrFullSrc: "",
        
            //车辆类型
            carType: 0,
            carTypeRange: [{
                name: '二手车',
                value: '0',
                checked: 'true'
              },
              {
                name: '新车',
                value: '1',
                disabled: true
              }
            ],
        
            //所属城市
            location: "",
        
            name: "",
            //过户次数
            transferTimesIndex: "",
            transferTimesRange: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
            //钥匙数量
            keyNumIndex: "",
            keyNumRange: [1, 2, 3, 4, 5],
            //出厂日期
            productionDate: "",
            //商业险有效期
            commerciaInsuranceDate: "",
            mandatoryInsuranceDate: "",
            //年检有效期
            examinationDate: "",
            //排放标准字段
           
            emissionStandardIndex: "",
        
            //车身颜色
            color: {
        
            },
        
            //车况描述是否可见
            remarkVisible: "0",
            //左前图片上传后返回的地址
            vehicleImagesLeftFrontImg: "",
            vehicleImagesLeftFrontImgBase64: "",
            vehicleImagesLeftFrontImgFullSrc: "",
            //右后
            vehicleImagesRightBackImg: "",
            vehicleImagesRightBackImgBase64: "",
            vehicleImagesRightBackImgFullSrc: "",
        
            //中控
            vehicleImagesConsoleImg: "",
            vehicleImagesConsoleImgBase64: "",
            vehicleImagesConsoleImgFullSrc: "",
            //座椅
            vehicleImagesSeatImg: "",
            vehicleImagesSeatImgBase64: "",
            vehicleImagesSeatImgFullSrc: "",
        
            //发动机舱
            vehicleImagesEngineImg: "",
            vehicleImagesEngineImgBase64: "",
            vehicleImagesEngineImgFullSrc: "",
        
            //后备箱
            vehicleImagesTrunkImg: "",
            vehicleImagesTrunkImgBase64: "",
            vehicleImagesTrunkImgFullSrc: "",
        
            vcLicenseImg: "",
            vcLicenseImgBase64: "",
            vcLicenseImgFullSrc: "",
        
        
            vcRegistration12Img: "",
            vcRegistration12ImgBase64: "",
            vcRegistration12ImgFullSrc: "",
        
            vcRegistrationLastImg: "",
            vcRegistrationLastImgBase64: "",
            vcRegistrationLastImgFullSrc: "",
        
            otherImgsStr: "",
            otherImgsStrBase64: [],
            otherImgsArr: []
        });
        this._initValidate();
        
      }
  },
  goBackToCarList: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  onReady: function () {
    /**
     * 获取对应车辆信息
     */
    if (this.data.opts.id) {
      //不是新增车辆
      Http.request({
        url: '/vehicleInfo/query/id',
        method: 'GET',
        data: {
          id: this.data.opts.id,
        },
        success: (res) => {
          console.log(res)

          this.data.remarkVisibleRange.forEach((item, index, self) => {
            if (item.value == res.remarkVisible) {
              item.checked = true
            } else {
              item.checked = ''
            }
          })

          this.data.carTypeRange.forEach((item, index, self) => {
            if (item.value == res.carType) {
              item.checked = true
            } else {
              item.checked = ''
            }
          })
          let info = transferInfo(res, this.data.useProperty, this.data.colorDicts)
          console.log(info)
          this.setData({
            info: info,
            licenseImgOcr: res.vehicleImages.certificationImgs.licenseImg,
            licenseImgOcrBase64: Utils.transformImageSrcBase64(res.thumbnails.certificationImgs.licenseImg),
            licenseImgOcrFullSrc: Utils.transformFullSrc(res.vehicleImages.certificationImgs.licenseImg),
            vin: res.vin,
            transferTimesIndex: res.transferTimes.toString(),
            remarkVisible: res.remarkVisible.toString(),
            remarkVisibleRange: this.data.remarkVisibleRange,
            mandatoryInsuranceDate: res.mandatoryInsuranceDate,
            color: info.color,
            location: info.location,
            registerDate: info.registerDate,
            productionDate: info.productionDate,
            examinationDate: info.examinationDate,
            mandatoryInsuranceDate: info.mandatoryInsuranceDate,
            commerciaInsuranceDate: info.commerciaInsuranceDate,
            keyNumIndex: info.keyNum-1,
            usePropertyIndex: this.data.usePropertyRange.indexOf(info.useProperty.name),
            //车辆类型
            carType: res.carType.toString(),
            carTypeRange: this.data.carTypeRange,
            //左前图片上传后返回的地址
            vehicleImagesLeftFrontImg: res.vehicleImages.leftFrontImg,
            vehicleImagesLeftFrontImgBase64: Utils.transformImageSrcBase64(res.thumbnails.leftFrontImg),
            vehicleImagesLeftFrontImgFullSrc: Utils.transformFullSrc(res.vehicleImages.leftFrontImg),
            //右后
            vehicleImagesRightBackImg: res.vehicleImages.rightBackImg,
            vehicleImagesRightBackImgBase64: Utils.transformImageSrcBase64(res.thumbnails.rightBackImg),
            vehicleImagesRightBackImgFullSrc: Utils.transformFullSrc(res.vehicleImages.rightBackImg),

            //中控
            vehicleImagesConsoleImg: res.vehicleImages.consoleImg,
            vehicleImagesConsoleImgBase64: Utils.transformImageSrcBase64(res.thumbnails.consoleImg),
            vehicleImagesConsoleImgFullSrc: Utils.transformFullSrc(res.vehicleImages.consoleImg),
            //座椅
            vehicleImagesSeatImg: res.vehicleImages.seatImg,
            vehicleImagesSeatImgBase64: Utils.transformImageSrcBase64(res.thumbnails.seatImg),
            vehicleImagesSeatImgFullSrc: Utils.transformFullSrc(res.vehicleImages.seatImg),

            //发动机舱
            vehicleImagesEngineImg: res.vehicleImages.engineImg,
            vehicleImagesEngineImgBase64: Utils.transformImageSrcBase64(res.thumbnails.engineImg),
            vehicleImagesEngineImgFullSrc: Utils.transformFullSrc(res.vehicleImages.engineImg),

            //后备箱
            vehicleImagesTrunkImg: res.vehicleImages.trunkImg,
            vehicleImagesTrunkImgBase64: Utils.transformImageSrcBase64(res.thumbnails.trunkImg),
            vehicleImagesTrunkImgFullSrc: Utils.transformFullSrc(res.vehicleImages.trunkImg),

            vcLicenseImg: res.vehicleImages.certificationImgs.licenseImg,
            vcLicenseImgBase64: Utils.transformImageSrcBase64(res.thumbnails.certificationImgs.licenseImg),
            vcLicenseImgFullSrc: Utils.transformFullSrc(res.vehicleImages.certificationImgs.licenseImg),


            vcRegistration12Img: res.vehicleImages.certificationImgs.registration12Img,
            vcRegistration12ImgBase64: Utils.transformImageSrcBase64(res.thumbnails.certificationImgs.registration12Img),
            vcRegistration12ImgFullSrc: Utils.transformFullSrc(res.vehicleImages.certificationImgs.registration12Img),

            vcRegistrationLastImg: res.vehicleImages.certificationImgs.registrationLastImg,
            vcRegistrationLastImgBase64: Utils.transformImageSrcBase64(res.thumbnails.certificationImgs.registrationLastImg),
            vcRegistrationLastImgFullSrc: Utils.transformFullSrc(res.vehicleImages.certificationImgs.registrationLastImg),

            otherImgsStr: res.thumbnails.otherImgs ? res.vehicleImages.otherImgs.join('|') : '',
            otherImgsStrBase64: res.thumbnails.otherImgs ? Utils.transformImageSrcBase64(res.thumbnails.otherImgs) :[],
            otherImgsArr:  res.vehicleImages.otherImgs ?  res.vehicleImages.otherImgs :""
          })
          console.log("info", this.data.info)
          console.log("otherImgsStrBase64", Utils.transformImageSrcBase64(res.thumbnails.otherImgs))
        }
      })
    }
  },

  /**
   * 排放标准-改变事件
   */
  bindEmissionStandardChange: function (e) {
    console.log('排放标准，携带值为', e.detail.value, this.data.emissionStandardRange[e.detail.value])
    this.setData({
      emissionStandardIndex: e.detail.value
    })
  },

  bindVinInput: function (e) {
    console.log('bindVinInput', e.detail.value)
    this.setData({
      vin: e.detail.value
    })
  },


  /**
   * 使用性质-改变事件
   */
  bindUsePropertyChange: function (e) {
    console.log('使用性质选择改变，携带值为', e.detail.value, this.data.usePropertyRange[e.detail.value])
    this.setData({
      usePropertyIndex: e.detail.value
    })
  },

  /**
   * 车辆类型选择-改变事件
   */
  bindCarTypeChange: function (e) {
    console.log('bindCarTypeChange，携带值为', e.detail.value)
    this.setData({
      carType: e.detail.value
    })
  },
  /**
   * 初登日期-改变事件
   */
  bindRegisterDateChange: function (e) {
    console.log('初登日期选择改变，携带值为', e.detail.value)
    this.setData({
      registerDate: e.detail.value
    })
  },
  /**
   * 是否可见-改变事件
   */
  bindRemarkVisibleChange: function (e) {
    console.log('bindRemarkVisibleChange，携带值为', e.detail.value)
    this.setData({
      remarkVisible: e.detail.value
    })
  },
  /**
   * 上传行驶证
   */
  bindUploadDrivelicense: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        wx.showLoading({
          title: "上传识别中"
        });
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: (res) => {
            let baseImg = 'data:image/jpeg;base64,' + res.data
            that.setData({
              licenseImgOcrBase64: baseImg
            });

            console.log(that.data.licenseImgOcr)
            //上传ocr并保存

            Http.request({
              url: "/image/ocrAndSave",
              method: 'POST',
              data: {
                imageType: 'VL',
                image: baseImg,
              },
              success: (res) => {
                console.log(res);
                wx.hideLoading()
                let src = Http.apiUrl + Http.imgUrl + "?imagePath=" + res.url +
                  "&" + wx.getStorageSync("sessionid");


                that.setData({
                  usePropertyIndex: that.data.usePropertyRange.indexOf(res.words_result['使用性质'].words),
                  vin: res.words_result['车辆识别代号'].words,
                  ['info.owner']: res.words_result['所有人'].words,
                  ['info.ownerAddress']: res.words_result['住址'].words,
                  registerDate: res.words_result['注册日期'].words.toString().replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'),
                  ['info.brandModel']: res.words_result['品牌型号'].words,
                  ['info.plateNo']: res.words_result['号牌号码'].words,

                  licenseImgOcr: res.url,
                  licenseImgOcrFullSrc: src
                });
              },
              error: function (res) {
                wx.hideLoading()
              }
            })
          },
          fail: () => {
            wx.hideLoading();
          }
        })
      }
    })
  },


  bindProgressStep3ImgLoad: function () {
    wx.hideLoading();
  },
  /**
   * 删除上传的行驶证
   */
  bindDelUploadDrivelicense: function () {
    this.setData({
      usePropertyIndex: "",
      vin: "",
      ['info.owner']: "",
      ['info.ownerAddress']: "",
      registerDate: "",
      ['info.brandModel']: "",
      ['info.plateNo']: "",
      licenseImgOcr: "",
      licenseImgOcrBase64: "",
      licenseImgOcrFullSrc: ""
    })
  },

  bindPicDel: function (e) {
    var dataSet = e.currentTarget.dataset;
    console.log('车辆所属地，携带值为', dataSet);

    if (dataSet.name == "vehicleImagesLeftFrontImg") {
      //左前
      this.setData({
        vehicleImagesLeftFrontImg: "",
        vehicleImagesLeftFrontImgBase64: "",
        vehicleImagesLeftFrontImgFullSrc: ""
      })
    } else if (dataSet.name == "vehicleImagesRightBackImg") {
      //右后
      this.setData({
        vehicleImagesRightBackImg: "",
        vehicleImagesRightBackImgBase64: "",
        vehicleImagesRightBackImgFullSrc: ""
      })
    } else if (dataSet.name == "vehicleImagesConsoleImg") {
      //中控
      this.setData({
        vehicleImagesConsoleImg: "",
        vehicleImagesConsoleImgBase64: "",
        vehicleImagesConsoleImgFullSrc: ""
      })
    } else if (dataSet.name == "vehicleImagesSeatImg") {
      //座椅
      this.setData({
        vehicleImagesSeatImg: "",
        vehicleImagesSeatImgBase64: "",
        vehicleImagesSeatImgFullSrc: ""
      })
    } else if (dataSet.name == "vehicleImagesEngineImg") {
      //发动机
      this.setData({
        vehicleImagesEngineImg: "",
        vehicleImagesEngineImgBase64: "",
        vehicleImagesEngineImgFullSrc: ""
      })
    } else if (dataSet.name == "vehicleImagesTrunkImg") {
      //后备箱
      this.setData({
        vehicleImagesTrunkImg: "",
        vehicleImagesTrunkImgBase64: "",
        vehicleImagesTrunkImgFullSrc: ""
      })
    } else if (dataSet.name == "vcLicenseImg") {
      this.setData({
        vcLicenseImg: "",
        vcLicenseImgBase64: "",
        vcLicenseImgFullSrc: ""
      })
    } else if (dataSet.name == "vcRegistration12Img") {
      this.setData({
        vcRegistration12Img: "",
        vcRegistration12ImgBase64: "",
        vcRegistration12ImgFullSrc: ""
      })
    } else if (dataSet.name == "vcRegistrationLastImg") {
      this.setData({
        vcRegistrationLastImg: "",
        vcRegistrationLastImgBase64: "",
        vcRegistrationLastImgFullSrc: ""
      })
    }
  },
  /**
   * 表单提交
   * step 第几步
   */
  bindFormSubmit: function (e) {
    const params = e.detail.value;
    console.log("bindFormSubmit", params, e);
    if (e.detail.target.dataset.type == "draft") {
      this.WxValidate = new WxValidate({}, {});
    }
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      console.log(error)
      wx.showToast({
        title: error.msg,
        icon: 'none',
        duration: 2000
      })
    } else {
      //通过验证
      if (this.data.progressStep == 1) {
        this.setData({
          progressStep: 2
        });
        !this.data.isDisabled && this._initValidate();
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
        /**
         * 通过vin码查询车型
         */
        Http.request({
          url: '/mall/vehicle/vin/query',
          method: 'GET',
          data: {
            vin: this.data.vin,
          },
          success: (res) => {
            if (!res) {
              wx.showToast({
                title: '无法匹配车型请手动选择',
                duration: 2000,
                icon: "none"
              })
            } else {
              if (res.carList) {
                this.setData({
                  carInfoForVin: res,
                  name: res.carList[0].name,
                  modelId: res.carList[0].carId
                });
              } else {
                wx.showToast({
                  title: '无法匹配车型请手动选择',
                  duration: 2000,
                  icon: "none"
                })
              }
            }

          }
        });
       
      } else if (this.data.progressStep == 2) {
        this.setData({
          progressStep: 3
        });
        !this.data.isDisabled && this._initValidate();
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
      } else if (this.data.progressStep == 3) {
        wx.showLoading({
          mask:true
        })
        if (e.detail.target.dataset.type == "draft") {
          Http.request({
            url: '/vehicleInfo/saveDraft',
            method: 'POST',
            data: params,
            success: (res) => {
              console.log(res),
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '保存草稿成功！',
                showCancel: false,
                confirmText: "我知道了",
                success(res) {
                  if (res.confirm) {
                    wx.navigateBack();
                  }
                }
              })
            },
            error:function(){
              wx.hideLoading();
            }
          });
        } else {
          //提交表单****************
          Http.request({
            url: "/vehicleInfo/commit",
            method: 'POST',
            data: params,
            success: (res) => {
              wx.hideLoading();
              wx.navigateTo({
                url: '/pages/sendCar/carAddResult/index',
              })
            },
            error:function(){
              wx.hideLoading();
            }
          })
        }

      }

    }
  },


  /**
   * 车辆所属地
   */
  // bindLocationChange: function (e) {
  //   console.log('车辆所属地，携带值为', e.detail.value);
  //   this.setData({
  //     // location: e.detail.value[0] + e.detail.value[1] + e.detail.value[2]
  //     location: e.detail.value[1]
  //   })
  // },
  /**
   * 年检有效期
   */
  bindExaminationDateChange: function (e) {
    console.log('年检有效期，携带值为', e.detail.value)
    this.setData({
      examinationDate: e.detail.value
    })
  },
  /**
   * 过户次数
   */
  bindTransferTimesChange: function (e) {
    console.log('过户次数，携带值为', e.detail.value)
    this.setData({
      transferTimesIndex: e.detail.value
    })
  },
  /**
   * 钥匙数量
   */
  bindkeyNumChange: function (e) {
    console.log('钥匙数量，携带值为', e.detail.value)
    this.setData({
      keyNumIndex: e.detail.value
    })
  },

  /**
   * 商业险到期日期
   */
  bindCommerciaInsuranceDateChange: function (e) {
    console.log('商业险到期日期，携带值为', e.detail.value)
    this.setData({
      commerciaInsuranceDate: e.detail.value
    })
  },
  /**
   * 交强险到期日期
   */
  bindMandatoryInsuranceDateChange: function (e) {
    console.log('交强险到期日期，携带值为', e.detail.value)
    this.setData({
      mandatoryInsuranceDate: e.detail.value
    })
  },
  /**
   * 出厂日期
   */
  bindProductionDateChange: function (e) {
    console.log('出厂日期日期，携带值为', e.detail.value)
    this.setData({
      productionDate: e.detail.value
    })
  },

  bindUploadCarImg: function (e) {
    var dataSet = e.currentTarget.dataset;
    var that = this;
    console.log("bindUploadCarImg", dataSet);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '图片上传中',
        })
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: (res) => {
            let baseImg = 'data:image/jpeg;base64,' + res.data
            Http.request({
              url: "/image/save",
              method: "POST",
              data: {
                image: baseImg
              },
              success: function (res) {
                console.log(res);
                let fullSrc = Http.apiUrl + Http.imgUrl + "?imagePath=" + res +
                  "&" + wx.getStorageSync("sessionid");
                //左前
                if (dataSet.name == "vehicleImagesLeftFrontImg") {
                  that.setData({
                    vehicleImagesLeftFrontImg: res,
                    vehicleImagesLeftFrontImgBase64: baseImg,
                    vehicleImagesLeftFrontImgFullSrc: fullSrc,
                  })
                } else if (dataSet.name == "vehicleImagesRightBackImg") {
                  //右后
                  that.setData({
                    vehicleImagesRightBackImg: res,
                    vehicleImagesRightBackImgBase64: baseImg,
                    vehicleImagesRightBackImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vehicleImagesConsoleImg") {
                  //中控
                  that.setData({
                    vehicleImagesConsoleImg: res,
                    vehicleImagesConsoleImgBase64: baseImg,
                    vehicleImagesConsoleImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vehicleImagesSeatImg") {
                  //座椅
                  that.setData({
                    vehicleImagesSeatImg: res,
                    vehicleImagesSeatImgBase64: baseImg,
                    vehicleImagesSeatImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vehicleImagesEngineImg") {
                  //发动机
                  that.setData({
                    vehicleImagesEngineImg: res,
                    vehicleImagesEngineImgBase64: baseImg,
                    vehicleImagesEngineImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vehicleImagesTrunkImg") {
                  //后备箱
                  that.setData({
                    vehicleImagesTrunkImg: res,
                    vehicleImagesTrunkImgBase64: baseImg,
                    vehicleImagesTrunkImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vcLicenseImg") {
                  that.setData({
                    vcLicenseImg: res,
                    vcLicenseImgBase64: baseImg,
                    vcLicenseImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vcRegistration12Img") {
                  that.setData({
                    vcRegistration12Img: res,
                    vcRegistration12ImgBase64: baseImg,
                    vcRegistration12ImgFullSrc: fullSrc
                  })
                } else if (dataSet.name == "vcRegistrationLastImg") {
                  that.setData({
                    vcRegistrationLastImg: res,
                    vcRegistrationLastImgBase64: baseImg,
                    vcRegistrationLastImgFullSrc: fullSrc
                  })
                }
                wx.hideLoading()
              },
              error: function (res) {
                wx.hideLoading()
              }
            })
          },
          fail: () => {
            wx.hideLoading();
          }
        })
      }
    })

  },
  /**
   * 删除其他车型
   */
  bindPicCarOthersDel: function (e) {
    var dataSet = e.currentTarget.dataset;
    this.data.otherImgsArr.splice(dataSet.idx, 1);
    this.data.otherImgsStrBase64.splice(dataSet.idx, 1);
    this.setData({
      otherImgsStrBase64: this.data.otherImgsStrBase64,
      otherImgsArr: this.data.otherImgsArr,
      otherImgsStr: this.data.otherImgsArr.join("|")
    });
    console.log('bindPicCarOthersDel', this.data.otherImgsArr, this.data.otherImgsStr, this.data.otherImgsStrBase64)

  },
  /**
   * 其他上传图片
   */
  bindUploadCarOthersImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 9 - this.data.otherImgsArr.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);

        res.tempFilePaths.forEach((item, index, self) => {
          wx.getFileSystemManager().readFile({
            filePath: item,
            encoding: 'base64', //编码格式
            success: (res) => {
              let baseImg = 'data:image/jpeg;base64,' + res.data;
              wx.showLoading();
              Http.request({
                url: "/image/save",
                method: "POST",
                data: {
                  image: baseImg
                },
                success: function (res) {

                  // let src = Http.apiUrl + Http.imgUrl + "?imagePath=" + res +
                  //   "&" + wx.getStorageSync("sessionid");
                  // var otherImgsArr = [...that.data.otherImgsArr];
                  that.setData({
                    otherImgsStrBase64: that.data.otherImgsStrBase64.concat([baseImg]),
                    otherImgsArr: that.data.otherImgsArr.concat([res])
                  });

                  that.setData({
                    otherImgsStr: that.data.otherImgsArr.join("|")
                  });
                  wx.hidesLoading();
                  console.log('bindUploadCarOthersImg', that.data.otherImgsArr, that.data.otherImgsStr)
                },
                error: function () {
                  wx.hideLoading();
                }
              })
            }
          })
        });
      }
    })
  },

  /**
   * 上一步
   */
  bindStepPre: function (e) {
    var dataSet = e.currentTarget.dataset;
    this.setData({
      progressStep: dataSet.step
    });
    this._initValidate();
  },
  /**
   * 选择颜色页面调用事件
   */
  pageCarColorChooseColor: function (data) {
    console.log('pageCarColorChooseColor', data);
    this.setData({
      color: data
    })
  },

  /**
   * 
   *车辆所属地选择

   */
  chooseCity: function (e) {
    let filed = this.data.location;
    let isDisabled = e.currentTarget.dataset.isDisabled;
    if (!isDisabled) {
      wx.navigateTo({
        url: '/pages/itemChose/index?filed=' + filed,
      })
    } else {
      return false;
    }
  },
  //选择回写所属地数据
  setdes: function (value) {
    this.setData({
      location: value
    })
  },
  /**
   * 选择汽车品牌调用事件
   */
  pageCarBrandChooseBrand: function (data) {
    console.log('pageCarBrandChooseBrand', data);
    this.setData({
      name: data.brand + ' ' + data.audi + ' ' + data.cartype,
      modelId: data.modelId
    })
  },

  /**
   * 配置亮点描述
   */
  pageConfigDetailHighlight: function (data) {
    console.log('pageConfigDetailHighlight', data);
    this.setData({
      detailHighlight: data.detailHighlight
    })
  },


  /**
   * 初始化表单验证规则
   */
  _initValidate: function () {
    let r1 = {},
      r2 = {},
      r3 = {};
    if (this.data.progressStep == 1) {
      r1 = {
        //行驶证
        licenseImgOcr: {
          required: true
        },

        //VIN码
        vin: {
          required: true
        },
        //车牌号
        plateNo: {
          required: true
        },
        //初次上牌时间
        registerDate: {
          required: true
        },
        //品牌型号
        brandModel: {
          required: true
        },
        //使用性质
        useProperty: {
          required: true
        },
        //车主姓名
        owner: {
          required: true
        },
        //车主住所
        ownerAddress: {
          required: true
        }
      }
    } else if (this.data.progressStep == 2) {
      r2 = {
        //表里程数
        mileage: {
          required: true,
          digits: true
        },

        //商城标价
        price: {
          required: true,
          digits: true
        },
        //品牌车型
        name: {
          required: true
        },
        //参数配置
        modelId: {
          required: true
        },
        //车身颜色
        color: {
          required: true
        },
        //排放标准
        emissionStandard: {
          required: true
        },
        //车辆所属地
        location: {
          required: true
        },
        //过户次数
        transferTimes: {
          required: true
        },
        //productionDate
        productionDate: {
          required: true
        },
        //年检到期日期
        examinationDate: {
          required: true
        },
        //交强险到期日期
        mandatoryInsuranceDate: {
          required: true
        },
        //商业险到期日期
        commerciaInsuranceDate: {
          required: true
        },
        keyNum: {
          required: true
        }
      }
    } else if (this.data.progressStep == 3) {
      r3 = {
        //左前
        'vehicleImages.leftFrontImg': {
          required: true
        },
        //右后
        'vehicleImages.rightBackImg': {
          required: true
        },
        //中控
        'vehicleImages.consoleImg': {
          required: true
        },
        //座椅
        'vehicleImages.seatImg': {
          required: true
        },
        //发动机舱
        'vehicleImages.engineImg': {
          required: true
        },
        //后备箱
        'vehicleImages.trunkImg': {
          required: true
        },
        //驾驶证
        'vehicleImages.certificationImgs.licenseImg': {
          required: true
        },
        //登记证第一,二页照片
        'vehicleImages.certificationImgs.registration12Img': {
          required: true
        },
        //含签注信息的最后两页照片
        'vehicleImages.certificationImgs.registrationLastImg': {
          required: true
        }
      }
    }
    const rules = {
      ...r1,
      ...r2,
      ...r3
    };
    const messages = {
      licenseImgOcr: {
        required: "请上传行驶证照片"
      },
      vin: {
        required: "请填写VIN码"
      },
      plateNo: {
        required: "请填写车牌号"
      },
      registerDate: {
        required: "请选择初次上牌时间"
      },
      brandModel: {
        required: "请填写品牌型号"
      },
      useProperty: {
        required: "请选择使用性质"
      },
      owner: {
        required: "请填写车主姓名"
      },
      ownerAddress: {
        required: "请填写车主住所"
      },

      //表里程数
      mileage: {
        required: "请填写表里程数",
        digits: "里程表数必须是数字"

      },
      //商城标价
      price: {
        required: "请填写商城标价",
        digits: "商城标价必须是数字"
      },
      //品牌车型
      name: {
        required: "请选择品牌车型"
      },
      //参数配置
      modelId: {
        required: "请填写参数配置"
      },
      //车身颜色
      color: {
        required: "请选择车身颜色"
      },
      //排放标准
      emissionStandard: {
        required: "请选择排放标准"
      },
      //车辆所属地
      location: {
        required: "请选择车辆所属地"
      },
      //过户次数
      transferTimes: {
        required: "请选择过户次数"
      },

      //productionDate
      productionDate: {
        required: "请选择生产日期"
      },
      //年检到期日期
      examinationDate: {
        required: "请选择年检到期日期"
      },
      //交强险到期日期
      mandatoryInsuranceDate: {
        required: "请选择交强险到期日期"
      },
      //商业险到期日期
      commerciaInsuranceDate: {
        required: "请选择商业险到期日期"
      },
      //钥匙数量
      keyNum: {
        required: "请选择钥匙数量"
      },

      //左前
      'vehicleImages.leftFrontImg': {
        required: "请上传汽车左前图片"
      },
      //右后
      'vehicleImages.rightBackImg': {
        required: "请上传汽车右后图片"
      },
      //中控
      'vehicleImages.consoleImg': {
        required: "请上传汽车中控台图片"
      },
      //座椅
      'vehicleImages.seatImg': {
        required: "请上传汽车座椅图片"
      },
      //发动机舱
      'vehicleImages.engineImg': {
        required: "请上传汽车发动机舱图片"
      },
      //后备箱
      'vehicleImages.trunkImg': {
        required: "请上传汽车后备箱图片"
      },
      //驾驶证
      'vehicleImages.certificationImgs.licenseImg': {
        required: "请上传驾驶证图片"
      },
      //登记证第一,二页照片
      'vehicleImages.certificationImgs.registration12Img': {
        required: "请上传登记证第一,二页照片"
      },
      //含签注信息的最后两页照片
      'vehicleImages.certificationImgs.registrationLastImg': {
        required: "请上传含签注信息的最后两页照片"
      }
    };
    this.WxValidate = new WxValidate(rules, messages);
  }


})